#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include "../inc/tcp.h"
#include "../inc/msg_popup.h"
#include "../inc/login.h"
#include "../inc/homepage.h"
#include "../inc/user_event.h"

char secv_buf[1024] = {0}; // 接收缓冲区

server_info_t server_info = {0}; // 服务器信息

// 全局连接状态标志
static volatile int connected     = 0;
static pthread_mutex_t conn_mutex = PTHREAD_MUTEX_INITIALIZER;

// 接收服务器返回的消息
void * get_message(void * arg)
{
    server_info_t * info = (server_info_t *)arg;

    while(1) {
        // 连接到服务器
        pthread_mutex_lock(&conn_mutex);
        if(!connected) {
            if(connect(info->sockfd, (struct sockaddr *)&info->addr, sizeof(info->addr)) < 0) {
                if(home_src != NULL) {
                    printf("断开连接 隐藏 home_src start\n");
                    lv_obj_add_flag(home_src, LV_OBJ_FLAG_HIDDEN); // 隐藏登录界面
                }
                if(login_src != NULL) {
                    printf("断开连接 显示 login_src start\n");
                    lv_obj_clear_flag(login_src, LV_OBJ_FLAG_HIDDEN);
                    sleep(1);
                    show_msg_box("与服务器断开连接", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
                    printf("断开连接  login_src 创建 over\n");
                }

                perror("connect error");

                pthread_mutex_unlock(&conn_mutex);
                sleep(3); // 等待后重试
                continue;
            }
            connected = 1;
            printf("服务器连接成功!\n");
        }
        pthread_mutex_unlock(&conn_mutex);

        int recv_len;

        // 接收消息
        recv_len = recv(info->sockfd, secv_buf, sizeof(secv_buf) - 1, 0);
        if(recv_len <= 0) {
            // 连接断开
            pthread_mutex_lock(&conn_mutex);
            connected = 0;
            pthread_mutex_unlock(&conn_mutex);
            printf("服务器连接断开，重新连接...\n");
            close(info->sockfd);
            // 重新创建socket
            info->sockfd = socket(AF_INET, SOCK_STREAM, 0);
            continue;
        }

        secv_buf[recv_len] = '\0'; // 确保字符串结束
        // printf("服务器消息: %s\n", secv_buf);
        parse_server_response(secv_buf);
    }

    return NULL;
}

// 发送消息到服务器
int send_message_to_server(server_info_t * info, char * msg)
{
    pthread_mutex_lock(&conn_mutex);
    if(!connected) {
        printf("未连接到服务器，无法发送消息\n");
        show_msg_box("未连接服务器", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
        pthread_mutex_unlock(&conn_mutex);
        return -1;
    }
    pthread_mutex_unlock(&conn_mutex);

    if(send(info->sockfd, msg, strlen(msg), 0) < 0) {
        perror("send error");
        // 发送失败，标记连接断开
        pthread_mutex_lock(&conn_mutex);
        connected = 0;
        pthread_mutex_unlock(&conn_mutex);
        return -1;
    }
    return 0;
}

// 发送消息线程
void * send_message(void * arg)
{
    server_info_t * info = (server_info_t *)arg;

    while(1) {
        // 等待连接建立
        pthread_mutex_lock(&conn_mutex);
        int is_connected = connected;
        pthread_mutex_unlock(&conn_mutex);

        if(!is_connected) {
            sleep(1);
            continue;
        }

        // 从用户输入获取消息
        char buf[1024];
        fgets(buf, sizeof(buf), stdin);

        // 去除换行符
        buf[strcspn(buf, "\n")] = 0;

        // 发送消息到服务器
        if(send_message_to_server(info, buf) == 0) {
            printf("已发送: %s\n", buf);
        }
    }

    return NULL;
}

// 初始化TCP客户端
int init_tcp_client(server_info_t * info)
{
    // 创建socket
    info->sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(info->sockfd < 0) {
        perror("socket creation failed");
        return -1;
    }

    // 设置服务器地址
    memset(&info->addr, 0, sizeof(info->addr));
    info->addr.sin_family      = AF_INET;
    info->addr.sin_port        = htons(SERVER_PORT);
    info->addr.sin_addr.s_addr = inet_addr(SERVER_IP);

    connected = 0;

    return 0;
}
